package com.akk.platform.oem;


import com.akk.module.app.entity.AppSharePic;
import com.akk.module.app.model.request.AppSharePicRequest;
import com.akk.module.app.service.AppSharePicService;
import com.akk.module.upload.service.PictureService;
import com.akk.utils.PageUtils;
import com.akk.utils.Query;
import com.akk.utils.RestResponse;
import com.akk.utils.ShiroUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/platform/oem/sharepic")
@Api(value = "oem-app",description = "OEM后台接口-APP分享")
public class AppSharePicAction {

    @Autowired
    private AppSharePicService sharePicService;

    @Autowired
    private PictureService pictureServices;

    @RequestMapping("/list")
    @RequiresPermissions("platform:oem:sharepic:list")
    public RestResponse shardPics(Query query){
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<AppSharePic> list = sharePicService.sharePicByAppId(ShiroUtils.getAdmin().getAppId());
        return RestResponse.build(PageUtils.buildPage(list,(int) new PageInfo<>(list).getTotal(),query));
    }

    @PostMapping("/save")
    @RequiresPermissions("platform:oem:sharepic:save")
    public RestResponse save(AppSharePicRequest request, HttpServletRequest servletRequest){
        if (request.getShareImgFile() == null)
            return RestResponse.build("1","请上传一张banner图片");
        Map<String,Object> map = pictureServices.uploadPicture(request.getShareImgFile());
        if (map.get("status").toString().equals("1"))
            return RestResponse.build("1","图片上传失败，请重试");
        String imageUrl = map.get("url").toString();
        request.setAppId(ShiroUtils.getAdmin().getAppId());
        request.setFileUrl(imageUrl);
        sharePicService.insert(request);
        return RestResponse.build("success");
    }

    @RequestMapping("/delete/{sid}")
    @RequiresPermissions("platform:oem:sharepic:delete")
    public RestResponse shardPics(@PathVariable Integer sid){
        AppSharePic sharePic = sharePicService.findById(sid);
        if (sharePic == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"资源不存在");
        if (sharePic.getFileUrl() != null)
            pictureServices.removeFile(sharePic.getFileUrl());
        sharePicService.delete(sid);
        return RestResponse.build("删除成功");
    }

}
